//
//  BeautyRecommViewController.swift
//  月升
//
//  Created by 拉利法 on 2024/7/9.
//

import UIKit
import ZLPhotoBrowser

class BeautyRecommViewController: QIBaseViewController {
    
    private var selectImg = UIImage()
    private var addBtn = UIButton()
    private var imgPreviewView = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "美妆推荐"

        addUI()
    }
    
    
    private func addUI() {
        showGradientColor()
        
        addBtn = UIButton().then {
            $0.backgroundColor = .orange
            $0.setImage(UIImage(named: "添加照片"), for: .normal)
            $0.addRoundedCorners(withRadius: 100)
            $0.addTarget(self, action: #selector(addBtnClick), for: .touchUpInside)
        }
        view.addSubview(addBtn)
        addBtn.mas_makeConstraints({ make in
            make?.centerX.equalTo()(self.view)
            make?.centerY.equalTo()(self.view.mas_centerY)?.offset()(-80)
            make?.size.sizeOffset()(CGSize(width: 200, height: 200))
        })
        
        let titleL = UILabel().then({
            $0.text = "请上传一张正脸素颜照"
            $0.textColor = Color666666
            $0.font = FONT(ofSize: 14)
        })
        view.addSubview(titleL)
        titleL.mas_makeConstraints({ make in
            make?.top.equalTo()(addBtn.mas_bottom)?.offset()(10)
            make?.centerX.equalTo()(self.view)
            make?.height.offset()(20)
        })
    }
    
    @objc private func addBtnClick() {
//        albumSlelect()
        let alertCtl = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        alertCtl.addAction(UIAlertAction(title: "从相册选择", style: .default, handler: { (_) in
//            let imagePickerCtl = UIImagePickerController()
//            imagePickerCtl.delegate = self
//            imagePickerCtl.allowsEditing = true
//            imagePickerCtl.sourceType = .savedPhotosAlbum
//            self.present(imagePickerCtl, animated: true)
            self.albumSlelect()
        }))
        alertCtl.addAction(UIAlertAction(title: "打开相机", style: .default, handler: { (_) in
//            let imagePickerCtl = UIImagePickerController()
//            imagePickerCtl.delegate = self
//            imagePickerCtl.allowsEditing = true
//            imagePickerCtl.sourceType = .camera
//            self.present(imagePickerCtl, animated: true)
            
            let ctl = QICameraViewController()
            ctl.delegate = self
            self.navigationController?.pushViewController(ctl, animated: true)
            
        }))
        alertCtl.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in
            
        }))
        self.present(alertCtl, animated: true)
    }
  
    
    private func albumSlelect() {
        ZLPhotoConfiguration.default().maxSelectCount = 1
        ZLPhotoConfiguration.default().allowSelectVideo = false
        ZLPhotoConfiguration.default().allowTakePhotoInLibrary = false
        ZLPhotoConfiguration.default().allowEditImage = true
        ZLPhotoConfiguration.default().useCustomCamera = true
        ZLPhotoUIConfiguration.default().sortAscending = false
        ZLPhotoUIConfiguration.default().columnCount = 3
        ZLPhotoUIConfiguration.default().cellCornerRadio = 5
        let ps = ZLPhotoPreviewSheet()
        ps.selectImageBlock = { [weak self] results, isOriginal in
            let image = results.first!.image
            print("当前分辨率\(image.size)")
            guard (image.size.width >= 1500 && image.size.height >= 2000) || (image.size.height >= 1500 && image.size.width >= 2000) else {
                ShowHUD(str: "请选择分辨率大于1500*2000的图片")
                return
            }
            self?.selectImg = image
//            self?.addBtn.setImage(results.first?.image, for: .normal)
            self?.addImagePreviewView(img: self!.selectImg)
        }
        ps.showPhotoLibrary(sender: self)
//        ps.showPreview(animate: true, sender: self)
    }
    
}


extension BeautyRecommViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate, WWXHCameraViewControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let image: UIImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
        picker.dismiss(animated: true)
        guard (image.size.width >= 1500 && image.size.height >= 2000) || (image.size.height >= 1500 && image.size.width >= 2000) else {
            ShowHUD(str: "请选择分辨率大于1500*2000的图片")
            print("当前分辨率\(image.size)")
            return
        }
        self.selectImg = image
        self.addImagePreviewView(img: image)
        
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true)
    }
    
    func cameraViewController(_: QICameraViewController, didFinishPickingImage image: UIImage) {
        guard (image.size.width >= 1500 && image.size.height >= 2000) || (image.size.height >= 1500 && image.size.width >= 2000) else {
            ShowHUD(str: "请选择分辨率大于1500*2000的图片")
            print("当前分辨率\(image.size)")
            return
        }
        self.selectImg = image
        self.addImagePreviewView(img: image)
    }
    
}



extension BeautyRecommViewController {
    
    /// 添加图片预览页面
    private func addImagePreviewView(img: UIImage) {
        addBtn.isHidden = true
        
        imgPreviewView = UIImageView().then {
            $0.frame = CGRect(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - NAV_HEIGHT - 200)
            $0.image = img
            $0.tag = 11
            $0.contentMode = .scaleAspectFill
            $0.clipsToBounds = true
        }
        view.addSubview(imgPreviewView)
        
        let cancelBtn = UIButton().then {
            $0.frame = CGRect(x: 40, y: imgPreviewView.bottom + 50, width: SCREEN_WIDTH / 2 - 50, height: 40)
            $0.tag = 12
            $0.titleLabel?.font = FONT(ofSize: 16)
            $0.setTitle("取消", for: .normal)
            $0.setTitleColor(MainColor, for: .normal)
            $0.addRoundedCorners(withRadius: 20)
            $0.addBorder(withWidth: 1, borderColor: MainColor)
            $0.addTarget(self, action: #selector(cancelBtnClick), for: .touchUpInside)
        }
        view.addSubview(cancelBtn)
        
        let confirmBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH / 2 + 10, y: cancelBtn.top, width: cancelBtn.width, height: 40)
            $0.backgroundColor = MainColor
            $0.tag = 12
            $0.titleLabel?.font = FONT(ofSize: 16)
            $0.setTitle("确认", for: .normal)
            $0.setTitleColor(.white, for: .normal)
            $0.addRoundedCorners(withRadius: 20)
            $0.addTarget(self, action: #selector(confirmBtnClick), for: .touchUpInside)
        }
        view.addSubview(confirmBtn)
        
    }
    
    private func addErrorView(errStr: String) {
        let bgView = UIView()
        bgView.frame = imgPreviewView.frame
        bgView.tag = 11
        bgView.backgroundColor = UIColor(white: 0, alpha: 0.2)
        view.addSubview(bgView)
        
        let tipsL = UILabel().then({
            $0.frame = CGRect(x: 0, y: bgView.height * 0.4, width: SCREEN_WIDTH, height: 60)
            $0.text = errStr
            $0.textAlignment = .center
            $0.textColor = .white
            $0.numberOfLines = 0
            $0.font = FONT(ofSize: 18)
        })
        bgView.addSubview(tipsL)
        
        let confirmBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH / 2 - 44, y: bgView.height * 0.6, width: 88, height: 32)
            $0.titleLabel?.font = FONT(ofSize: 16)
            $0.setTitle("确定", for: .normal)
            $0.setTitleColor(.white, for: .normal)
            $0.addRoundedCorners(withRadius: 16)
            $0.addBorder(withWidth: 1, borderColor: .white)
            $0.addTarget(self, action: #selector(selectImgClick), for: .touchUpInside)
        }
        bgView.addSubview(confirmBtn)
    }
    
    @objc private func cancelBtnClick() {
        addBtn.isHidden = false
        view.subviews.forEach { vv in
            if vv.tag == 11 || vv.tag == 12 {
                vv.removeFromSuperview()
            }
        }
    }
    @objc private func confirmBtnClick() {
        
        HUD.flash(.labeledProgress(title: "", subtitle: "图片上传中..."), delay: 60)
        QINetworkManager.uploadImageDetection(urlStr: "/Skin/detection", image: selectImg) { json in
            HUD.hide()
            let model = json.dictionaryObject?.kj.model(QIDictBaseModel.self) ?? QIDictBaseModel()
            guard model.code == 1 else {
                ShowHUD(str: model.msg)
                self.addErrorView(errStr: model.msg)
                
                self.view.subviews.forEach { vv in
                    if vv.tag == 13 {
                        vv.removeFromSuperview()
                    }
                    if vv.tag == 12 {
                        vv.isHidden = false
                    }
                }
                
                return
            }
            
            let dataJson = json["data"]
            let raw_file_path = dataJson["raw_file_path"].stringValue
            let event_name = dataJson["event_name"].stringValue
            let url = dataJson["url"].stringValue
            
            self.jumpSkinAnalysis(raw_file_path: raw_file_path, event_name: event_name, imgUrl: url)
        } fail: { _ in
            HUD.hide()
            self.view.subviews.forEach { vv in
                if vv.tag == 13 {
                    vv.removeFromSuperview()
                }
                if vv.tag == 12 {
                    vv.isHidden = false
                }
            }
        }
        
        
        view.subviews.forEach { vv in
            if vv.tag == 12 {
                vv.isHidden = true
            }
        }
        
        let testBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH / 2 - 46, y: imgPreviewView.bottom + 20, width: 92, height: 92)
            $0.tag = 13
            $0.addRoundedCorners(withRadius: 46)
            $0.addBorder(withWidth: 10, borderColor: MainColor)
        }
        view.addSubview(testBtn)
        
        let titleL1 = UILabel().then({
            $0.frame = CGRect(x: 0, y: testBtn.bottom + 6, width: SCREEN_WIDTH, height: 17)
            $0.tag = 13
            $0.text = "照片已上传成功"
            $0.textColor = Color999999
            $0.textAlignment = .center
            $0.font = FONT(ofSize: 12)
        })
        view.addSubview(titleL1)
        
        let titleL2 = UILabel().then({
            $0.frame = CGRect(x: 0, y: titleL1.bottom + 6, width: SCREEN_WIDTH, height: 22)
            $0.tag = 13
            $0.text = "AI正在分析皮肤状态"
            $0.textColor = Color999999
            $0.textAlignment = .center
            $0.font = FONTBOLD(ofSize: 16)
        })
        view.addSubview(titleL2)
        
        
    }
    @objc private func selectImgClick() {
        cancelBtnClick()
    }
    
    @objc private func jumpSkinAnalysis(raw_file_path: String, event_name: String, imgUrl: String) {
        
        HUD.flash(.labeledProgress(title: "", subtitle: "数据获取中..."), delay: 60)
        let param = [
            "raw_file_path": raw_file_path,
            "event_name": event_name,
            "image": imgUrl
        ]
        
        QINetworkManager.requestJson(urlStr: "/Skin/skin", parameters: param) { json in
            print(json)
            HUD.hide()
            let resultModel = json["skin"].dictionaryObject?.kj.model(QISkinAnalysisResultsModel.self) ?? QISkinAnalysisResultsModel()
            
            let ctl = SkinAnalysisViewController()
            ctl.img = self.selectImg
            ctl.raw_file_path = raw_file_path
            ctl.event_name = event_name
            ctl.resultModel = resultModel
//            ctl.wuGuanModel = wuGuanModel
            ctl.originalImgUrl = imgUrl
            self.navigationController?.pushViewController(ctl, animated: true)
            
            self.cancelBtnClick()
            self.view.subviews.forEach { vv in
                if vv.tag == 13 {
                    vv.removeFromSuperview()
                }
            }
        } fail: { json in
            HUD.hide()
            self.cancelBtnClick()
            self.view.subviews.forEach { vv in
                if vv.tag == 13 {
                    vv.removeFromSuperview()
                }
            }
        }

    }
}
